package game.module.club.dao;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Files;

import game.module.club.bean.ClubNameUsedBean;
import game.module.template.ClubNameTemplate;
import lion.common.Reloadable;

/**
 * @author: Pomelo.Lee
 * @date: 2017年8月29日 上午10:37:22
 */
public class ClubNameTemplateCache implements Reloadable {

	private static Logger logger = LoggerFactory.getLogger(ClubNameTemplateCache.class);

	static class SingletonHolder {
		static ClubNameTemplateCache instance = new ClubNameTemplateCache();
	}

	public static ClubNameTemplateCache getInstance() {
		return SingletonHolder.instance;
	}

	private transient List<ClubNameTemplate> templateList;

	private Map<String, ClubNameTemplate> map = new ConcurrentHashMap<>();

	@Override
	public void reload() {

		try {
			String jsonStr = Files.asCharSource(new File("data/clubname.json"), Charset.forName("UTF-8")).read();
			ObjectMapper mapper = new ObjectMapper();
			templateList = mapper.readValue(jsonStr, new TypeReference<List<ClubNameTemplate>>() {
			});
			clearUsedClubName();
			logger.info("size={}", map.size());
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	private void clearUsedClubName() {
		for (ClubNameTemplate ct : templateList) {
			map.put(ct.getName(), ct);
		}
		List<ClubNameUsedBean> list = ClubDao.getInstance().listAllUsedClubName();
		if (list == null || list.size() <= 0) {
			return;
		}
		for (ClubNameUsedBean cub : list) {
			if (map.containsKey(cub.getClubName())) {
				map.remove(cub.getClubName());
			}
		}
	}

	public ClubNameTemplate getRandomTemplate() {
		Collection<ClubNameTemplate> ct = map.values();
		int rn = RandomUtils.nextInt(0, ct.size());
		ClubNameTemplate[] ctArray = ct.toArray(new ClubNameTemplate[0]);
		return ctArray[rn];
	}

	public boolean removeUsedName(String clubName) {
		if (map.containsKey(clubName)) {
			map.remove(clubName);
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		ClubNameTemplateCache ctc = ClubNameTemplateCache.getInstance();
		ctc.reload();

		ClubNameTemplate ct = ctc.getRandomTemplate();
		System.out.println(ct.getName());
	}

}
